package com.simple.system.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.simple.system.entity.Result;
import com.simple.system.service.ActivitiService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/activiti")
@CrossOrigin(origins = "*", maxAge = 3600)
public class ActivitiController {

    @Autowired
    private ActivitiService activitiService;

    @GetMapping("/start")
    public String start(){
        return "hello";
    }

    @GetMapping("/startLeaveProcess")
    public String startLeaveProcess(@RequestParam String applicant, @RequestParam String approver) {
        return activitiService.startLeaveProcess(applicant, approver);
    }

    @GetMapping("/tasks/{assignee}")
    public Result<JSONArray> getTasks(@PathVariable String assignee) {
        List<Task>  list = activitiService.getTasksByAssignee(assignee);
        JSONArray jsonArray = new JSONArray();
        for (Task task : list) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",task.getId());
            jsonObject.put("name", task.getName());
            jsonObject.put("assignee", task.getAssignee());
            jsonArray.add(jsonObject);
        }

        return Result.success(jsonArray);
    }

    @GetMapping("/tasks/complete/{taskId}")
    public Result<String> completeTask(@PathVariable String taskId) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("approvalResult", true);
        activitiService.completeTask(taskId,variables);
        return Result.success("审批成功");
    }
}